const express = require('express')
const ajaxRouter = express.Router()
const cookieParser = require('cookie-parser')
const { formStudyUserLists } = require("../model/formStudyUserLists.js")

ajaxRouter.use(cookieParser())

// 电话本
ajaxRouter.get('/telBook', (req, res) => {
    res.render('index', { url: './ajax/telBook' })
})

// 文件上传
ajaxRouter.get('/uploadFile', (req, res) => {
    res.render('index', { url: './ajax/uploadFile' })
})

// 文件上传的临时页面 
ajaxRouter.get('/uploadTmp', (req, res) => {
    res.render('index', { url: './ajax/uploadTmp' })
})

// ajax方法封装
ajaxRouter.get('/packaging', (req, res) => {
    res.render('index', { url: './ajax/packaging' })
})

// JSONP方法封装
ajaxRouter.get('/jsonpPackaging', (req, res) => {
    res.render('index', { url: './ajax/jsonpPackaging' })
})

// 省市区三级联动菜单
ajaxRouter.get('/threeMenuSelect', (req, res) => {
    res.render('index', { url: './ajax/threeMenuSelect' })
})


/* form表单提交数据案例相关路由开始 */
ajaxRouter.get('/register', (req, res) => {
    if (req.cookies.user) {
        res.redirect('/ajax/login')
    } else {
        res.render('index', { url: './ajax/register' })
    }
})
ajaxRouter.get('/login', (req, res) => {
    if (!req.cookies.user) {
        res.redirect('/ajax/register')
    } else {
        res.render('index', { url: './ajax/login' })
    }
})
ajaxRouter.get('/home', async(req, res) => {
    if (!req.cookies.user) {
        res.redirect('/ajax/register')
    } else {
        let queryResult = await formStudyUserLists.findOne({ name: req.cookies.user });
        res.render('index', { url: './ajax/home', userInfo: queryResult })
    }
})
ajaxRouter.post('/register', async(req, res) => {
    res.cookie('user', req.body.name)
    let addResult = await formStudyUserLists.create(req.body);
    res.redirect('/ajax/login');
})
ajaxRouter.post('/login', async(req, res) => {
        let name = req.body.name;
        let password = req.body.password;
        let queryResult = await formStudyUserLists.find({ name: name });

        if (queryResult.length > 0) {
            if (queryResult[0].password === password) {
                res.redirect('/ajax/home');
            } else {
                res.redirect('/ajax/login');
            }
        } else {
            res.redirect('/ajax/login');
        }
    })
    /* form表单提交数据案例相关路由结束 */


module.exports = ajaxRouter;